on findLastTargetIndex(targetItem, itemList)
	set lastIndex to 0
	repeat with i from (count of itemList) to 1 by -1
		if item i of itemList is targetItem then
			set lastIndex to i
			exit repeat
		end if
	end repeat
	return lastIndex
end findLastTargetIndex
beep 1
say "Starting Sidecar"
beep 1

tell application "System Settings"
	activate
	delay 1
	tell application "System Events"
		tell process "System Settings"
			click menu item "Displays" of menu "View" of menu bar item "View" of menu bar 1
			delay 0.3
			tell group 1 of group 2 of splitter group 1 of group 1 of window "Displays"
				try
					-- Wait for "Add" button to appear
					set buttonFound to false
					set timeoutSeconds to 10 -- Timeout in seconds
					set startTime to current date
					repeat
						try
							-- Try to get the "Add" button
							set addButton to pop up button "Add"
							set buttonFound to true
							exit repeat
						on error
							-- If button not found, check for timeout
							if (current date) - startTime > timeoutSeconds then
								say "Timeout: Add button not found"
								return
							end if
							delay 0.5 -- Wait 0.5 seconds before retrying
						end try
					end repeat
					
					-- If "Add" button found, continue
					if buttonFound then
						click addButton
						-- Get all menu item names
						set menuItems to name of menu items of menu "Add" of pop up button "Add"
						-- Find the last index of our target item
						set targetIndex to (my findLastTargetIndex("LiDongDongiPadPro", menuItems))
						-- Click the target menu item
						delay 0.3
						click menu item targetIndex of menu "Add" of pop up button "Add"
						say "Operation successful, Sidecar connected or disconnected"
					end if
				on error
					delay 0.5
					say "Not found or error occurred: " & errorMessage
					exit repeat
				end try
			end tell
		end tell
	end tell
end tell
delay 1
beep 1
tell application "System Settings" to quit
